<!-- TableComponent.vue -->
<template>
  <div class="table">
    <div class="wrapper main-card selector-wrapper">
      <el-button type="info" class="add" plain @click="dialogVisible = true"
        >新增模板</el-button
      >
    </div>
    <!-- 主页面 -->
    <el-table :data="pageData">
      <el-table-column prop="MoneyName" label="模板名称"></el-table-column>
      <el-table-column prop="Money" label="收费标准"></el-table-column>
      <!-- <el-table-column label="模板状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value="1"
            inactive-value="0"
            @change="handleSwitchChange(scope.row)"
          >
          </el-switch>
        </template>
</el-table-column> -->
      <el-table-column
        prop="MoneyObj"
        label="收费对象"
        :formatter="formatSubsidyObject"
      ></el-table-column>
      <!-- <el-table-column prop="subsidy_time" label="补助"></el-table-column> -->
      <!-- <el-table-column prop="createdAt" label="修改时间"></el-table-column> -->
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="upbutton(scope.row)">修改</el-button>
          <el-button type="primary" @click="bindBuilding(scope.row)"
            >绑定楼栋</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 弹窗 -->
    <el-dialog
      title="新增模板"
      :visible.sync="dialogVisible"
      width="800px"
      class="cleaner-dialog"
      :before-close="cleanSelected"
    >
      <el-form class="form" ref="form" :model="formData">
        <el-form-item label="模板名称">
          <el-input
            v-model.trim="formData.MoneyNam"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="收费标准">
          <el-input
            v-model.trim="formData.Money"
            placeholder="请输入"
          ></el-input>
        </el-form-item>

        <!-- <el-form-item label="修改日期"> -->
        <!-- <el-select v-model.trim="formData.subsidy_time" placeholder="请选择" :clearable="true">
          <el-option
            v-for="item in subsidy_time"
            :key="item.id"
            :label="item.obj"
            :value="item.obj"
          >
          </el-option>
       </el-select> -->
        <!-- <div>
            <SelectMonths
              ref="selectMonths"
              v-model="formData.subsidy_time"
              placeholder="请选择月份"
              @submitBtn="submitBtn"
              @resetBtn="resetBtn"
            />
          </div>
        </el-form-item> -->

        <el-form-item label="修改对象">
          <el-select
            v-model.trim="formData.MoneyObj"
            placeholder="请选择"
            :clearable="true"
          >
            <el-option
              v-for="item in obj"
              :key="item.id"
              :label="item.obj"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible3" title="楼栋选择" width="300px">
      <el-select
        v-model="selectedBuildingIds"
        multiple
        placeholder="请选择楼栋"
        style="width: 240px"
      >
        <el-option
          v-for="item in buildOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible3 = false">取消</el-button>
          <el-button type="primary" @click="bindMeter">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog
      title="模板信息"
      :visible.sync="dialogVisible2"
      width="800px"
      class="cleaner-dialog"
      :before-close="cleanSelected"
    >
      <el-form class="form" ref="form" :model="formData2">
        <el-form-item label="模板名称">
          <el-input
            v-model.trim="formData2.MoneyName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="收费标准">
          <el-input
            v-model.trim="formData2.Money"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="补助周期(月)">
          <div>
            <SelectMonths
              ref="selectMonths"
              v-model="monthsValue"
              placeholder="请选择月份"
              @submitBtn="submitBtn2"
              @resetBtn="resetBtn2"
            />
          </div>
        </el-form-item> -->
        <el-form-item label="收费对象">
          <!-- <el-input v-model.trim="formData2.contract" placeholder="请输入"></el-input> -->
          <el-select
            v-model.trim="formData2.MoneyObj"
            placeholder="请选择"
            :clearable="true"
          >
            <el-option
              v-for="item in obj"
              :key="item.id"
              :label="item.obj"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible2 = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit2">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import { getsubsidys, upsubsidys, insubsidys } from '@/api/meter.js'
import { getmeterbases, upsubsidys, insubsidys } from '@/api/subsidytemplate.js'
import SelectMonths from './SelectMonths.vue'
import { addtemplate } from '@/api/template.js'
import { bindpaytype } from '@/api/bind'
import { getManageBuildings } from '@/api/building'
export default {
  components: {
    SelectMonths
  },

  name: 'RentTable',
  data() {
    return {
      monthsValue: [],
      // 显示主页面
      showMain: true,
      // 显示租金页面
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      building: [],
      tableData: [],
      currentPage: 1,
      pageData: [],
      total: '',
      pageSize: 10,
      selectData: '',
      buildOptions: [
        {
          value: '1',
          label: '楼栋一'
        },
        {
          value: '2',
          label: '楼栋二'
        }
      ],
      obj: [
        { id: 1, obj: '学生', value: 'student' },
        { id: 2, obj: '老师', value: 'teacher' },
        { id: 3, obj: '职工', value: 'workers' }
      ],
      subsidy_time: [
        { id: 1, obj: '一个月' },
        { id: 2, obj: '三个月' },
        { id: 3, obj: '半年' }
      ],
      value5: '',
      formData: {
        subsidy_name: '',
        MoneyObj: '',
        subsidy_money: '',
        subsidy_time: ''
      },
      formData2: {},
      selectedBuildingIds: [], // Store selected building IDs
      currentTemplate: null // Store the template being bound
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    bindBuilding(row) {
      this.currentTemplate = row // Store the template being bound
      getManageBuildings()
        .then(res => {
          this.buildOptions = res.data.buildings.map(item => {
            return {
              value: item.id,
              label: item.name
            }
          })
          // Load previously selected buildings if any
          if (row.buildings && row.buildings.length > 0) {
            this.selectedBuildingIds = row.buildings.map(b => b.id)
          } else {
            this.selectedBuildingIds = []
          }
          this.dialogVisible3 = true
        })
        .catch(error => {
          this.$message.error('获取楼栋数据失败')
          console.error(error)
        })
    },

    bindMeter() {
      if (!this.selectedBuildingIds || this.selectedBuildingIds.length === 0) {
        this.$message.warning('请至少选择一个楼栋')
        return
      }

      if (!this.currentTemplate) {
        this.$message.error('未找到模板信息')
        return
      }

      const bindData = {
        buildingId: [...this.selectedBuildingIds],
        meterbases: this.currentTemplate
      }
      console.log(bindData)

      bindpaytype(bindData)
        .then(res => {
          console.log(res.success)

          if (res.success) {
            this.$message.success('绑定成功')
            this.dialogVisible3 = false
            // Refresh data to show updated bindings
            this.fetchData()
          } else {
            this.$message.error(res.message || '绑定失败')
            this.dialogVisible3 = false
          }
        })
        .catch(error => {
          this.$message.error('绑定请求失败')
          console.error(error)
          this.dialogVisible3 = false
        })
    },
    // 实现分页的方法
    queryByPage() {
      // 起始位置 = (当前页 - 1) x 每页的大小
      const start = (this.currentPage - 1) * this.pageSize
      // 结束位置 = 当前页 x 每页的大小
      const end = this.currentPage * this.pageSize

      return this.tableData.slice(start, end)
    },
    handleSizeChange(val) {
      this.pageSize = val

      this.pageData = this.queryByPage()
    },
    handleCurrentChange(val) {
      this.currentPage = val

      this.pageData = this.queryByPage()
    },

    submitBtn(val) {
      const months = JSON.parse(JSON.stringify(val))
      this.formData.subsidy_time = months.join(',')
    },
    resetBtn() {
      this.formData.subsidy_time = null
    },
    submitBtn2(val) {
      const months = JSON.parse(JSON.stringify(val))
      this.monthsValue = months.join(',')
    },
    resetBtn2() {
      this.monthsValue = null
    },
    formatSubsidyObject(row) {
      if (row.MoneyObj === 'student') {
        return '学生'
      }
      if (row.MoneyObj === 'teacher') {
        return '老师'
      }
      if (row.MoneyObj === 'workers') {
        return '职工'
      }
      // 如果有其他情况，可以继续添加判断和对应的返回值
      // else if (row.subsidy_obj === 'otherValue') {
      //   return '其他文本';
      // }
      // ...
      else {
        return row.MoneyObj
      }
    },
    // 获取服务器数据
    fetchData() {
      // 数据接口
      getmeterbases().then(res => {
        console.log(res)
        this.tableData = res.data.meterbases
        this.total = res.data.meterbases.length
        this.pageData = res.data.meterbases
      })
    },
    //新增
    handleSubmit() {
      console.log(this.formData)

      insubsidys(this.formData).then(res => {
        if (res.success == true) {
          this.$message.success('新增成功')
          this.dialogVisible = false
          this.fetchData()
        }
      })
    },
    //修改
    handleSubmit2() {
      this.formData2.subsidy_time = this.monthsValue

      upsubsidys(this.formData2).then(res => {
        if (res.success == true) {
          this.$message.success('修改成功')
          this.dialogVisible2 = false
          this.fetchData()
        }
      })
    },

    upbutton(rwo) {
      console.log(rwo)
      this.formData2 = rwo
      this.monthsValue = ''
      console.log(this.formData2)
      console.log(this.monthsValue)

      this.dialogVisible2 = true
    },
    cleanSelected() {
      // 重置表单数据
      this.formData = {
        subsidy_name: '',
        MoneyObj: '',
        subsidy_money: '',
        subsidy_time: ''
      }
      this.dialogVisible = false
      // 如果有其他需要清理的数据，也可以在这里添加
    }
  }
}
</script>

<style scoped>
.search {
  width: 400px;
  margin: 20px 20px 20px 0px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.wrapper {
  margin: 40px 0;
}

.add {
  float: right;
  padding: 9px 15px;
  font-size: 12px;
  border-radius: 3px;
}

.el-select {
  display: block;
  position: relative;
  position: relative;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  /* Adjust margin as needed */
}
</style>
